package com.cookie.framework.manager;

import com.cookie.framework.cloud.CloudManager;
import com.cookie.framework.utils.SHA1;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import static com.cookie.framework.cloud.CloudManager.TOKEN_URL;

/**
 * 项目名:    MeetProject
 * 包名:      com.cookie.framework.manager
 * 文件名:    HttpManager
 * 创建者:    cookie
 * 创建时间:   2020/1/12 2:00
 * 描述:      OkHttp
 */

public class HttpManager {

    private static volatile HttpManager instance = null;
    private OkHttpClient httpClient;

    private HttpManager() {
        httpClient = new OkHttpClient();
    }

    public static HttpManager getInstance() {
        if (instance == null) {
            synchronized (HttpManager.class) {
                if (instance == null) {
                    instance = new HttpManager();
                }
            }
        }
        return instance;
    }

    //请求融云token
    public String postCloudToken(HashMap<String, String> map) {
        //参数
        String Timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String Nonce = String.valueOf(Math.floor(Math.random() * 100000));
        String Signature = SHA1.sha1(CloudManager.CLOUD_SECRET + Nonce + Timestamp);

        //参数填充
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : map.keySet()) {
            builder.add(key, map.get(key));
        }
        RequestBody requestBody = builder.build();
        //添加签名规则
        Request request = new Request.Builder()
                .url(CloudManager.TOKEN_URL)
                .addHeader("Timestamp", Timestamp)
                .addHeader("App-Key", CloudManager.CLOUD_KEY)
                .addHeader("Nonce", Nonce)
                .addHeader("Signature", Signature)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .post(requestBody)
                .build();
        try {
            return httpClient.newCall(request).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
